package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.pojo.User;
import com.example.pojo.UserMessage;
import com.example.service.UserFriendsService;
import com.example.service.UserMessageService;
import com.example.service.UserService;
import com.example.utils.Result;
import com.example.utils.TokenUtils;
import com.example.vo.UserFriendsVo;
import com.example.vo.UserMessageVo;
import com.example.wx.WebSocketEndPoint;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private WebSocketEndPoint webSocketEndPoint;

    @Autowired
    private UserService userService;
    @Autowired
    private UserMessageService userMessageService;

    @Autowired
    private UserFriendsService userFriendsService;
    @PostMapping("/login")
    public Result login(@RequestBody User user, HttpSession session) {
//       user判空
        try {
            if (user.getUsername() == null && user.getPassword() == null) {
                return Result.fail("账号密码为空");
            }
            User userSql = userService.getOne(new LambdaQueryWrapper<User>()
                    .eq(User::getUsername, user.getUsername())
                    .eq(User::getPassword, user.getPassword()));
            //判断账号密码是否正确
            if (userSql != null) {
                String token = TokenUtils.sign(userSql);
                return Result.ok(token);
            }
        } catch (Exception e) {
            return Result.fail("登录失败");
        }
        return Result.fail("登录失败");
    }

//    查询所有在线的用户id
    @GetMapping("/getOnlineMembers")
    public Result getOnlineMembers() {
//        用一个集合存储所有在线的用户id和名称
        // 用一个集合存储所有在线的用户id和名称
        List<Map<String, String>> onlineMembers = new ArrayList<>();
//        创建一个临时用户
        User user = new User();

        // 获取所有在线用户的ID或名称
        CopyOnWriteArrayList<String> allOnlineMembers = webSocketEndPoint.getOnlineMembers();

        for (String memberId : allOnlineMembers) {
            // 假设 memberId 是用户的ID
            // 需要从数据库或其他地方获取对应的用户名
            // 这里假设有一个方法 getUserById(String id) 返回用户的名称
            user = userService.getById(memberId);
            Map<String, String> member = new HashMap<>();
            member.put("id", memberId);
            member.put("name", user.getName());
            member.put("img", user.getImg());
            onlineMembers.add(member);
        }

        return Result.ok(onlineMembers);
    }

//    根据id查询用户名称
    @GetMapping("/getUserName/{userId}")
    public Result getUserName(@PathVariable("userId") Integer id) {
//        判空
        if (id==null){
            return Result.fail("用户ID为空");
        }
        User user = userService.getById(id);
        return Result.ok(user.getName());
    }


//    查询用户ID的所有朋友
    @GetMapping("/getFriends/{id}")
    public Result getFriends(@PathVariable("id") Integer id , UserFriendsVo userFriendsVo) {
        if (id==null){
            return Result.fail("用户ID为空");
        }
        return userFriendsService.getFriends(id, userFriendsVo);
    }

//    查询历史记录
    @GetMapping("/getHistory/{receiveUserId}")
    public Result getHistory(@PathVariable("receiveUserId") String  receiveUserId,HttpServletRequest request) {
        if (receiveUserId==null){
            return Result.fail("用户ID为空");
        }
//        根据token拿到当前的用户id
        String sendUserId = TokenUtils.getUserFromToken(request.getHeader("token")).getId();
        return userFriendsService.getHistory(sendUserId,receiveUserId);
    }

//    保存历史记录
    @PostMapping("/saveHistory")
    public Result saveHistory(@RequestBody UserMessage userMessage) {
        return userFriendsService.saveHistory(userMessage);
    }

    /**
     * 处理私聊
     */
    /**
     * 发送点对点的聊天消息
     *
     * @return
     */
    @PostMapping("/sendChatMsg")
    @Transactional
    public Result sendChatMsg(@RequestBody UserMessageVo userMessageVo, HttpServletRequest request) {
        //先判断toUserId是否存在
        if (userMessageVo.getReceiveUserId() == null) {
            return Result.fail("接受者Id为空");
        }
//        根据token拿到发送者id
        String token = request.getHeader("token");
        String sendUserId = TokenUtils.getUserFromToken(token).getId();
        if (sendUserId == null || "".equalsIgnoreCase(sendUserId)){
            return Result.fail("发送者Id为空");
        }
        try {
            HashMap<String, Object> objectObjectHashMap = new HashMap<>();
            //类型：private，个人设置，我这里是私聊
            objectObjectHashMap.put("type", "private");
            //发送者id
            objectObjectHashMap.put("sendUserId", sendUserId);
            //聊天内容
            objectObjectHashMap.put("content", userMessageVo.getContent());
            //接受者id
            objectObjectHashMap.put("receiveUserId", userMessageVo.getReceiveUserId());
//            判断消息是否已经直接发送了
            Boolean aBoolean = webSocketEndPoint.handlePrivateMessage(objectObjectHashMap);
//            直接发送成功,然后把消息传给前端

            if (aBoolean) {
                log.info("发送成功");
            }
//            数据持久化，直接存入到数据库中
            UserMessage userMessage = new UserMessage();
            userMessage.setSendUserId(sendUserId);
            userMessage.setReceiveUserId(userMessageVo.getReceiveUserId());
            userMessage.setContent(userMessageVo.getContent());
//            直接消息设置为1
            userMessage.setSendTime(new Date());
            log.info("保存消息到数据库{}", userMessage);
            userMessageService.save(userMessage);
        } catch (Exception e) {
            log.error("发送失败", e);
            throw new RuntimeException("发送失败");
        }
        return Result.ok("发送成功");
    }
    @GetMapping("getUserNameById/{id}")
    public Result getUserById(@PathVariable("id") String  id) {
        if (id==null || "".equals(id)){
            return Result.fail("用户ID为空");
        }
        User user = userService.getById(id);
        return Result.ok(user);
    }
    /**
     * 根据token来获取用户id
     */
    @GetMapping("/getUserIdByToken/{token}")
    public Result getUserIdByToken(@PathVariable("token") String  token) {
        if (token==null || "".equals(token)){
            return Result.fail("token为空");
        }
        String userId = TokenUtils.getUserFromToken(token).getId();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId,userId);
        User user = userService.getOne(queryWrapper);
        return Result.ok(user);
    }




}
